import './index.css'
import {trimStr} from '@/util/dom/index.js'
import {_User} from '@/service/user-service.js'

let _ErrMsg = {
	show : function(errTip){
		
		let errItem = document.getElementsByClassName('error-item')[0]
		errItem.setAttribute("style","display:block");
		let errMsg =  errItem.getElementsByClassName('err-msg')[0]
		if(errTip){
			errMsg.innerHTML = errTip;
		}
		
	},
	hide : function(){
		console.log("run")
		document.getElementsByClassName('error-item')[0].setAttribute("style","display:none");
	}
}

let _Register = {
	init : function(){
		console.log("run")
		this.bindEvent()

	},
	bindEvent : function(){
		document.getElementById('submit').addEventListener('click',() => {
			this.submit()
		}),
		document.getElementById('username').addEventListener('blur', () => {
			let username = trimStr(document.getElementById('username').value)
			_User.checkUsername(username,(res) => {
				console.log(res)
				if(res.status === 1){
					console.log("register success")
				}
				_ErrMsg.show("username has exist")
			},(errMsg) => {
				console.log(errMsg)
			})
		})
	},
	submit : function(){
		let data = {
			username : trimStr(document.getElementById("username").value),
			password : trimStr(document.getElementById("password").value),
			passwordConfirm : trimStr(document.getElementById("password-confirm").value),
			phone : trimStr(document.getElementById("phone").value),
			email : trimStr(document.getElementById("email").value),
			question : trimStr(document.getElementById("question").value),
			answer : trimStr(document.getElementById("answer").value)
		}
		
		//console.log(data);
		let result = this.validation(data)
		if(result.status){
			delete data.passwordConfirm
			_User.register(data, (res) => {
				console.log(res)
			}, (errMsg) => {
				console.log(errMsg)
			})
		}else{
			_ErrMsg.show(result.msg)
		}

	},
	validation : function(param){
		let result = {
			msg:'',
			status : false
		}

		if(param.username === ''){
			result.msg = 'username is null'
			return result
		}
		if(param.password === ''){
			result.msg = 'password is null'
			return result
		}

        // 验证密码长度
        if(param.password.length < 6){
            result.msg = '密码长度不能少于6位';
            return result;
        }
        // 验证两次输入的密码是否一致
        if(param.password !== param.passwordConfirm){
            result.msg = '两次输入的密码不一致';
            return result;
        }
       
        // 验证密码提示问题是否为空
        if(param.question === ''){
            result.msg = '密码提示问题不能为空';
            return result;
        }
        // 验证密码提示问题答案是否为空
        if(param.answer === ''){
            result.msg = '密码提示问题答案不能为空';
            return result;
        }
        // 通过验证，返回正确提示
        result.status   = true;
        result.msg      = '验证通过';
        return result;
	}
};

(() => {
	_Register.init();
})()